<script setup lang="ts">
import {onBeforeUnmount, onMounted, ref} from 'vue';
import {WebCodecsDecoder} from './WebCodecsDecoder';

const props = defineProps({
  url: String
})

let decoder: WebCodecsDecoder | null = null
const canvas = ref(null)

onMounted(() => {
  console.log('显示')
  onGotCanvas(canvas.value!)

  /*uni-app用此方法
  const query = uni.createSelectorQuery().in(this);
  query.select("#canvas").fields({node: true, size: true}).exec((res) => {
    const canvas = res[0].node;
    onGotCanvas(canvas)
  });
  */
});

const onGotCanvas = (canvas: HTMLCanvasElement) => {
  if (!canvas){
    console.log('canvas is null');
    return
  }
  decoder = new WebCodecsDecoder(canvas);
  //开始收流
  console.log('开始收流', props.url!);
  const socket = new WebSocket(props.url!);
  socket.binaryType = 'arraybuffer'; // WebSocket 接收二进制数据
  socket.onmessage = (e) => {
    const h264Data = new Uint8Array(e.data)
    decoder!.decode({
      type: 'data',
      data: h264Data,
      keyframe: true,
    });
  };
}

onBeforeUnmount(() => {
  console.log('销毁播放器')
  decoder!.dispose();
});

</script>

<template>
  <canvas id="canvas" ref="canvas" style="background-color:black; width:250px;height:500px"></canvas>
</template>
